package com.tangly.codeing.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tangly.codeing.dao.FileDao;
import com.tangly.codeing.model.File;
import com.tangly.codeing.service.FileService;
import com.tangly.codeing.utils.FastDfsData;
import com.tangly.codeing.utils.ReturnT;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;

/**
 * 文章
 *
 * @author tangbing
 * @date 2019-10-30
 */
@Service
public class FileServiceImpl implements FileService {

    private Logger logger = LoggerFactory.getLogger(FileServiceImpl.class);

    @Resource
    private FileDao fileDao;
    @Resource
    private FileService fileService;
    @Resource(name = "myThreadPoolExecutor")
    private Executor threadPoolExecutor;
    @Value("${file.dfsUrl}")
    private String dfsUrl;

    @Override
    public ReturnT<String> fileToDfsServer(String fileId) {
        List<File> list = new ArrayList<>();
        if (StringUtils.equals(fileId, "0")) {
            list = fileService.getAll();
        } else {
            File file = fileService.selectByPrimaryKey(Long.parseLong(fileId));
            list.add(file);
        }
        for (File file : list) {
            threadPoolExecutor.execute(() -> {
                //文件地址
                java.io.File tempFile = new java.io.File(file.getPath());
                //声明参数集合
                HashMap<String, Object> paramMap = new HashMap<>();
                //文件
                paramMap.put("file", tempFile);
                paramMap.put("filename", file.getName());
                //输出
                paramMap.put("output", "json");
                //上传
                String result = HttpUtil.post(dfsUrl, paramMap);
                logger.info("go-fastDFS文件上传返回:\n{}", result);
                Map mapTypes = JSON.parseObject(result);
                file.setRemark(mapTypes.get("url").toString());
                file.setKeys(mapTypes.get("md5").toString());
                fileService.updateByPrimaryKey(file);
            });
        }
        return ReturnT.SUCCESS;
    }

    @Override
    public List<File> getAll() {
        return fileDao.getAll();
    }

    @Override
    public File selectByPrimaryKey(Long id) {
        return fileDao.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKey(File record) {
        return fileDao.updateByPrimaryKey(record);
    }
}
